package Chapter2;

public class CirSinglyList<T> extends SinglyList<T> {
    public Node<T> head;

    public CirSinglyList() {
        this.head = new Node<T>();
        this.head.next = this.head;
    }

    public CirSinglyList(T[] values) {
        this();
        Node<T> rear = this.head;
        for (int i = 0; i < values.length; i++) {
            if (values[i] != null) {
                rear.next = new Node<T>(values[i], null);
                rear = rear.next;
            }
        }
        rear.next = this.head;
    }

    public CirSinglyList(CirSinglyList<T> list) {
        this();
        Node<T> rear = this.head;
        for (Node<T> p = list.head.next; p.next != this.head; p = p.next) {
            rear.next = new Node<T>(p.data, null);
            rear = rear.next;
        }
        rear.next = this.head;
    }

    public boolean isEmpty() {
        return this.head.next == this.head;
    }

    public T get(int i) {
        Node<T> p = this.head.next;
        for (int j = 0; p.next!=this.head && j < i; j++)
            p = p.next;
        return (i >= 0 && p.next!=this.head) ? p.data : null;
    }

    public void set(int i, T x) {
        Node<T> p = this.head.next;
        for (int j = 0; p.next!=this.head && j < i; j++)
            p = p.next;
        p.data = x;
    }

    public int size() {
        int i = 0;
        for (Node<T> p = this.head.next; p.next!=this.head; p = p.next)
            i++;
        return i;
    }

    public String toString() {
        String str = this.getClass().getName() + "(";
        for (Node<T> p = this.head.next; p != this.head; p = p.next)
            str += p.data.toString() + (p.next != this.head ? "," : "");
        return str + ")";
    }
}
